package com.jxs.android.sxyw;

import java.io.IOException;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.xmlpull.v1.XmlPullParserException;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;

import com.jxs.android.soap.BuWebService;
import com.jxs.android.soap.IWebService;
import com.jxs.android.sxyw.boot.SelfApplication;
import com.jxs.android.sxyw.data.UserInfo;
import com.jxs.android.sxyw.data.UserInfo.Role;
import com.jxs.android.sxyw.db.BusinessHolder;
import com.jxs.android.sxyw.db.GradeHolder;
import com.jxs.android.sxyw.db.HitchHolder;
import com.jxs.android.sxyw.db.OrgHolder;
import com.jxs.android.sxyw.db.SystemParamHolder;
import com.jxs.android.sxyw.weiget.PopMsg;
import com.jxs.android.sxyw.weiget.TopBar;
import com.jxs.android.util.StartHelper;
import com.jxs.android.util.StringUtils;
import com.jxs.android.util.SysUpdateHolder;
import com.jxs.android.util.VersionHolder;

public class Login extends AbstractActivity implements OnClickListener {

	private EditText userNameEd;
	private EditText passwordEd;
	private Button loginButton;
	private CheckBox remberPwdCb;

	private Context context;
	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		initTopBar(savedInstanceState, R.layout.login);
		context = this;
		userNameEd = (EditText) findViewById(R.id.login_username_input);
		passwordEd = (EditText) findViewById(R.id.login_password_input);
		remberPwdCb = (CheckBox) findViewById(R.id.remumber_pwd);

		String username = SystemParamHolder.getParamValue(SystemParamHolder.Keys.LOGIN_USER_NAME);

		if (!StringUtils.isEmpety(username)) {
			userNameEd.setText(username);
			userNameEd.setSelection(username.length());
			String password = SystemParamHolder.getParamValue(SystemParamHolder.Keys.LOGIN_USER_PWD);
			if (!StringUtils.isEmpety(password)) {
				passwordEd.setText(password);
			}
		}

		loginButton = (Button) findViewById(R.id.login_button);
		loginButton.setOnClickListener(this);

		remberPwdCb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					SystemParamHolder.saveOrUpdate(SystemParamHolder.Keys.LOGIN_USER_NAME, userNameEd.getText().toString());
					SystemParamHolder.saveOrUpdate(SystemParamHolder.Keys.LOGIN_USER_PWD, passwordEd.getText().toString());
				} else {
					SystemParamHolder.saveOrUpdate(SystemParamHolder.Keys.LOGIN_USER_NAME, "");
					SystemParamHolder.saveOrUpdate(SystemParamHolder.Keys.LOGIN_USER_PWD, "");
				}
			}
		});
	}

	@Override
	public void topBarLogic(TopBar topBar) {
		topBar.hindAllBtn();
		topBar.setTitle(R.string.app_name);
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == loginButton.getId()) {
			String usernameValue = userNameEd.getText().toString();
			String passWordValue = passwordEd.getText().toString();
			if (StringUtils.isEmpety(usernameValue)) {
				PopMsg.show("请输入用户名");
			} else if (StringUtils.isEmpety(passWordValue)) {
				PopMsg.show("请输入用密码");
			} else {
				progressDialog = ProgressDialog.show(this, "", "登录中，请稍候...", true);
				progressDialog.setCancelable(true);
				login(usernameValue, passWordValue);
				if (remberPwdCb.isChecked()) {
					SystemParamHolder.saveOrUpdate(SystemParamHolder.Keys.LOGIN_USER_NAME, userNameEd.getText().toString());
					SystemParamHolder.saveOrUpdate(SystemParamHolder.Keys.LOGIN_USER_PWD, passwordEd.getText().toString());
				}
			}

		}
	}

	public void login(final String userName, final String password) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				String wsdl_url = SelfApplication.WSDL_URL;// wsdl
				String namespace = SelfApplication.WSDL_NAME_SPACE;// namespace
				String methodName = "login";// 要调用的方法名称
				SoapObject request = new SoapObject(namespace, methodName);
				// request.addProperty("logonName", "jtrenyafeng");
				request.addProperty("logonName", userName);
				request.addProperty("password", password);
				TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
				String imsi = null == tm.getSubscriberId() ? "0" : tm.getSubscriberId();
				request.addProperty("imsiCode", imsi);
				request.addProperty("imeiCode", ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceId());
				request.addProperty("systemVersion", android.os.Build.VERSION.RELEASE);
				request.addProperty("clientVersion", VersionHolder.getVersionName(context));
				request.addProperty("longitude", "105");
				request.addProperty("latitude", "44");
				BuWebService webService = new BuWebService(wsdl_url, request);
				webService.setDoNet(false);
				webService.requestWSDL(new IWebService() {
					@Override
					public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
						SoapObject response = (SoapObject) envelope.getResponse();
						paser(response);
					}
				});
			}
		}).start();
	}

	private void paser(SoapObject soapObject) {
		String stauts = soapObject.getPropertySafelyAsString("status");
		SoapObject msgObjec = (SoapObject) soapObject.getProperty("msg");
		String message = msgObjec.getPropertySafelyAsString("message");
		if ("-2".equals(stauts)) {
			Message msg = new Message();
			msg.what = UPDATE_VERSION;
			String objs[] = new String[2];
			objs[0] = message;
			objs[1] = soapObject.getPropertySafelyAsString("url");
			msg.obj = objs;
			handler.sendMessage(msg);
		} else if ("-1".equals(stauts)) {
			Message msg = new Message();
			msg.what = ERROR_MSG;
			msg.obj = message;
			handler.sendMessage(msg);
		} else if ("0".equals(stauts)) {
			SoapObject userObject = (SoapObject) soapObject.getProperty("user");
			if (null != userObject) {
				UserInfo userInfo = new UserInfo();
				userInfo.setAccount_name(userObject.getPropertySafelyAsString("account_name"));
				userInfo.setCarrier_id(userObject.getPropertySafelyAsString("carrier_id"));
				userInfo.setCarrier_name(userObject.getPropertySafelyAsString("carrier_name"));
				userInfo.setCompany_id(userObject.getPropertySafelyAsString("company_id"));
				userInfo.setCompany_name(userObject.getPropertySafelyAsString("company_name"));
				userInfo.setMaintain_business(userObject.getPropertySafelyAsString("maintain_business"));
				userInfo.setMaintain_business_name(userObject.getPropertySafelyAsString("maintain_business_name"));
				userInfo.setSpecialty_id(userObject.getPropertySafelyAsString("specialty_id"));
				userInfo.setTelcom_flag(userObject.getPropertySafelyAsString("telcom_flag"));
				userInfo.setTicket(userObject.getPropertySafelyAsString("ticket"));
				userInfo.setUser_id(userObject.getPropertySafelyAsString("user_id"));
				userInfo.setUser_name(userObject.getPropertySafelyAsString("user_name"));

				String postion = userObject.getPropertySafelyAsString("position");
				if (!StringUtils.isEmpety(postion)) {
					if ("1".equals(postion.trim())) {
						userInfo.setRole(Role.MAINTAINER);
					} else if ("2".equals(postion.trim())) {
						userInfo.setRole(Role.MANAGER);
					} else if ("3".equals(postion.trim())) {
						userInfo.setRole(Role.DISPACHERR);
					}
				} else {
					userInfo.setRole(Role.NULL);
				}

				SelfApplication.setUserInfo(userInfo);
				initConfigData(soapObject);
			}

			Message msg = new Message();
			msg.what = LOGIN_ON;
			msg.obj = message;
			handler.sendMessage(msg);
		}
	}

	private void initConfigData(final SoapObject soapObject) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				SoapObject configObject = (SoapObject) soapObject.getProperty("config");
				if (null != configObject) {
					// 业务数据
					updatePropertyTypeList(SystemParamHolder.Keys.BUSINESS_UPDATE_DATE, configObject.getPropertySafelyAsString(SystemParamHolder.Keys.BUSINESS_UPDATE_DATE));
					// 隐患程度
					updatePropertyTypeList(SystemParamHolder.Keys.GRADE_UPDATE_DATE, configObject.getPropertySafelyAsString(SystemParamHolder.Keys.GRADE_UPDATE_DATE));
					// 地市县数据
					getOrgTableList(SystemParamHolder.Keys.CITY_UPDATE_DATE, configObject.getPropertySafelyAsString(SystemParamHolder.Keys.CITY_UPDATE_DATE));
					// 故障原因
					getBugTypeTableList(SystemParamHolder.Keys.HITCH_TYPE_DATE, configObject.getPropertySafelyAsString(SystemParamHolder.Keys.COUNTRY_UPDATE_DATE));
				}
			}
		}).start();

	}

	private void updatePropertyTypeList(final String key, final String value) {
		int temp_type = 0;
		int counter = 0;

		if (SystemParamHolder.Keys.BUSINESS_UPDATE_DATE.equals(key)) {
			temp_type = 1;
			counter = BusinessHolder.counter();
		} else if (SystemParamHolder.Keys.GRADE_UPDATE_DATE.equals(key)) {
			temp_type = 2;
			counter = GradeHolder.counter();
		}

		String dbValue = SystemParamHolder.getParamValue(key);

		final int type = temp_type;
		if (StringUtils.isEmpety(dbValue) || !value.equals(dbValue) || counter == 0) {
			String wsdl_url = SelfApplication.WSDL_URL;// wsdl
			String namespace = SelfApplication.WSDL_NAME_SPACE;// namespace
			String methodName = "getPropertyTypeList";// 要调用的方法名称
			SoapObject request = new SoapObject(namespace, methodName);
			request.addProperty("ticket", SelfApplication.getUserInfo().getTicket());
			request.addProperty("type", type);
			BuWebService webService = new BuWebService(wsdl_url, request);
			webService.setDoNet(false);
			webService.requestWSDL(new IWebService() {
				@Override
				public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
					SoapObject response = (SoapObject) envelope.getResponse();
					paserPropertyTypeList(response, type);
					SystemParamHolder.saveOrUpdate(key, value);
				}
			});
		}
	}

	private void getOrgTableList(final String key, final String value) {
		String dbValue = SystemParamHolder.getParamValue(key);
		int counter = OrgHolder.counter();
		if (StringUtils.isEmpety(dbValue) || !value.equals(dbValue) || counter == 0) {
			String wsdl_url = SelfApplication.WSDL_URL;// wsdl
			String namespace = SelfApplication.WSDL_NAME_SPACE;// namespace
			String methodName = "getOrgTableList";// 要调用的方法名称
			SoapObject request = new SoapObject(namespace, methodName);
			request.addProperty("ticket", SelfApplication.getUserInfo().getTicket());
			BuWebService webService = new BuWebService(wsdl_url, request);
			webService.setDoNet(false);
			webService.requestWSDL(new IWebService() {
				@Override
				public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
					SoapObject response = (SoapObject) envelope.getResponse();
					paserPropertyTypeList(response, 3);
					SystemParamHolder.saveOrUpdate(key, value);
				}
			});
		}
	}

	private void getBugTypeTableList(final String key, final String value) {
		String dbValue = SystemParamHolder.getParamValue(key);
		int counter = HitchHolder.counter();
		if (StringUtils.isEmpety(dbValue) || !value.equals(dbValue) || counter == 0) {
			String wsdl_url = SelfApplication.WSDL_URL;// wsdl
			String namespace = SelfApplication.WSDL_NAME_SPACE;// namespace
			String methodName = "getBugTypeTableList";// 要调用的方法名称
			SoapObject request = new SoapObject(namespace, methodName);
			request.addProperty("ticket", SelfApplication.getUserInfo().getTicket());
			BuWebService webService = new BuWebService(wsdl_url, request);
			webService.setDoNet(false);
			webService.requestWSDL(new IWebService() {
				@Override
				public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
					SoapObject response = (SoapObject) envelope.getResponse();
					paserPropertyTypeList(response, 4);
					SystemParamHolder.saveOrUpdate(key, value);
				}
			});
		}
	}

	private void paserPropertyTypeList(SoapObject soapObject, int type) {
		if (null != soapObject) {
			String stauts = soapObject.getPropertySafelyAsString("status");
			if ("-2".equals(stauts)) {
			} else if ("-1".equals(stauts)) {
			} else if ("0".equals(stauts)) {
				SoapObject retMsgObject = (SoapObject) soapObject.getProperty("retMsg");
				for (int i = 0; i < retMsgObject.getPropertyCount(); i++) {
					SoapObject taskBeanObject = (SoapObject) retMsgObject.getProperty(i);
					if (type == 1) {
						BusinessHolder.saveOrUpdate(taskBeanObject.getPropertySafelyAsString("id"), taskBeanObject.getPropertySafelyAsString("name"));
					} else if (type == 2) {
						GradeHolder.saveOrUpdate(taskBeanObject.getPropertySafelyAsString("id"), taskBeanObject.getPropertySafelyAsString("name"));
					} else if (type == 3) {
						String flag = taskBeanObject.getPropertySafelyAsString("flag");
						String org_id = taskBeanObject.getPropertySafelyAsString("org_id");
						String org_name = taskBeanObject.getPropertySafelyAsString("org_name");
						String parent_org_id = taskBeanObject.getPropertySafelyAsString("parent_org_id");
						OrgHolder.saveOrUpdate(org_id, org_name, parent_org_id, flag);
					} else if (type == 4) {
						String flag = taskBeanObject.getPropertySafelyAsString("flag");
						String id = taskBeanObject.getPropertySafelyAsString("id");
						String name = taskBeanObject.getPropertySafelyAsString("name");
						String parent_id = taskBeanObject.getPropertySafelyAsString("parent_id");
						HitchHolder.saveOrUpdate(id, name, parent_id, flag);
					}
				}
			}
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	private int LOGIN_ON = 0x110;
	private int UPDATE_VERSION = 0x111;
	private int ERROR_MSG = 0x112;

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (null != progressDialog && progressDialog.isShowing()) {
				progressDialog.cancel();
			}
			if (msg.what == LOGIN_ON) {
				PopMsg.show((String) msg.obj);
				StartHelper.startActivity(new Intent(context, Main.class));
				finish();
			} else if (msg.what == ERROR_MSG) {
				PopMsg.show((String) msg.obj);
			} else if (msg.what == UPDATE_VERSION) {
				String objs[] = (String[]) msg.obj;
				SysUpdateHolder.showUpdataDialog(Login.this, objs[0], "下载新版本", objs[1]);
			}
		}

	};
}
